package com.easyaccount.service;

import com.easyaccount.bean.LoginUser;
import com.easyaccount.bean.UserVO;
import com.easyaccount.commons.CommonResp;
import com.easyaccount.commons.TablePage;
import com.easyaccount.dao.*;
import com.easyaccount.exception.BizException;
import com.easyaccount.model.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class UserService {
    @Resource
    private MenuService menuService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private DeptMapper deptMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private RoleMapper roleMapper;

    public CommonResp save(UserVO userVO){
        User user = null;
        user = userMapper.selectByPhone(userVO.getPhone());
        if(user != null) throw new BizException("电话已存在",444);

        user = userMapper.selectByEmail(userVO.getEmail());
        if(user != null) throw new BizException("邮箱已存在",444);

        if (user == null) user = new User();
        BeanUtils.copyProperties(userVO,user);
        String pwd = userVO.getPhone().substring(5); // 初始密码为手机号后6位
        user.setPassword(pwd);
        user.setDeptId(userVO.getDept().getDeptId());
        userMapper.insertSelective(user);

        UserRole userRole = new UserRole();
        userRole.setRoleId(userVO.getRole().getRoleId());
        userRole.setUserId(user.getId());
        userRoleMapper.insertSelective(userRole);

        return CommonResp.success();
    }

    public CommonResp login(LoginUser loginUser, HttpSession session){

        User user = userMapper.selectByPhoneOrEmail(loginUser);
        if(user == null) return CommonResp.failed("用户不存在",444);

        if(!loginUser.getPassword().equals(user.getPassword())){
            return CommonResp.failed("密码错误",444);
        }else{
            BeanUtils.copyProperties(user,loginUser);
            Dept dept = deptMapper.selectByPrimaryKey(user.getDeptId());
            Role role = getRole(user.getId());
            loginUser.setRole(role);
            loginUser.setDeptName(dept.getDeptName());
            List<Menu> menus = menuService.getMenu(user.getId());
            loginUser.setMenus(menuService.toTree(menus));
            session.setAttribute("user",loginUser); // 将用户对象存入session

            System.out.println(loginUser);
            return CommonResp.success();
        }
    }

    public User getUserById(Integer id){
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    public CommonResp updateUser(UserVO userVO){
        User user = new User();
        BeanUtils.copyProperties(userVO,user);
        user.setDeptId(userVO.getDept().getDeptId());

        if(user.getId() == 1) throw new BizException("不允许删除管理员",444);
        int i = userMapper.selectByIdAndEmailCount(user);
        if (i > 0) throw new BizException("邮箱已存在",444);
        i = userMapper.selectByIdAndPhoneCount(user);
        if (i > 0) throw new BizException("电话已存在",444);

        userMapper.updateByPrimaryKeySelective(user);

        userRoleMapper.updateByUserId(user.getId(),userVO.getRole().getRoleId());
        return CommonResp.success();
    }

    public CommonResp updateUserPwd(User user){
        if(user.getId() == 1) throw new BizException("不允许删除管理员",444);
        userMapper.updateByPrimaryKeySelective(user);
        return CommonResp.success();
    }

    public CommonResp delete(User user){
        if(user.getId() == 1) throw new BizException("不允许删除管理员",444);

        User result = userMapper.selectByPrimaryKey(user.getId());
        if(result == null) throw new BizException("用户不存在",444);

        int i = userMapper.deleteByPrimaryKey(user.getId());
        if (i == 0) throw new BizException("删除失败",444);

        return CommonResp.success();
    }

    private Role getRole(Integer userId){
        UserRole userRole = userRoleMapper.selectByUserId(userId);    // 通过userid获取roleid
        Role role = roleMapper.selectByPrimaryKey(userRole.getRoleId());    // 通过roleid获取role
        return role;
    }

    public TablePage list(TablePage tablePage, String searchValue){
        int size = tablePage.getLimit();
        int start = (tablePage.getPage() - 1) * size;
        List<UserVO> userVOS = userMapper.selectPage(start, size, searchValue);
        int count = userMapper.selectPageCount(start, size, searchValue);
        tablePage.setCount(count);
        tablePage.setData(userVOS);
        return tablePage;
    }
}
